/**
 * 
 */
package com.hfjyz.examination.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.hfjyz.examination.dao.BaseDao;

/**
 *
 */
public abstract class BaseDaoImpl<T, PK extends Serializable> implements
		BaseDao<T, PK> {
	protected Logger log = LoggerFactory.getLogger(this.getClass());

	private Class<T> entityClazz;

	protected BaseDaoImpl(Class<T> entityClazz) {
		this.entityClazz = entityClazz;
	}

	@SuppressWarnings("unchecked")
	@Override
	public PK add(T entity) throws Exception {
		log.debug(" add entity: " + entity);
		return (PK) hibernateTemplate.save(entity);
	}

	@Override
	public void update(T entity) throws Exception {
		hibernateTemplate.update(entity);
	}

	@Override
	public void delete(T entity) throws Exception {
		hibernateTemplate.delete(entity);
	}

	@Override
	@SuppressWarnings("unchecked")
	public T get(PK pk) throws Exception {
		return (T) hibernateTemplate.get(entityClazz, pk);
	}

	@Override
	public void updateAll(List<T> entities) throws Exception {
		for (T entity : entities) {
			hibernateTemplate.update(entity);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<PK> addAll(List<T> entities) throws Exception {
		List<PK> pks = new ArrayList<PK>();
		for (T entity : entities) {
			pks.add((PK) hibernateTemplate.save(entity));
		}
		return pks;
	}

	@Override
	public void deleteAll(List<T> entities) throws Exception {

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> listAll() throws Exception {
		return (List<T>) hibernateTemplate.loadAll(entityClazz);
	}

	protected HibernateTemplate hibernateTemplate;

	/**
	 * @return the hibernateTemplate
	 */
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	/**
	 * @param hibernateTemplate
	 *            the hibernateTemplate to set
	 */
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

}
